package com.pets.web.job;

import com.alibaba.fastjson2.JSONObject;
import com.pets.common.utils.StringUtils;
import com.pets.web.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@Slf4j
@Component
public class AccessTokenJob {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${wx.globalAccessToken}")
    private String globalAccessToken;
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;

    public void refreshAccessToken(){
        String url = String.format(globalAccessToken, appId, secret);
        JSONObject result = restTemplate.getForObject(url, JSONObject.class);
        Objects.requireNonNull(result, "请求微信accessToken返回为空！");
        String errmsg = result.getString("errmsg");
        if (StringUtils.isNotEmpty(errmsg)) {
            log.error("请求微信accessToken报错: {}", result);
            return;
        }
        String accessToken = result.getString("access_token");
        log.info("------------->刷新accessToken: {}", accessToken);
        redisTemplate.opsForValue().set(Constant.ACCESS_TOKEN, accessToken);
    }
}
